<?php

namespace App\Http\Controllers\Api\Admin;

use App\Classify;
use App\Enterprise;
use App\EnterpriseUser;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Merchant;
use App\MerchantMedicine;
use App\Orders;
use App\SystemMedicine;
use App\User;
use App\UserInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LookController extends Controller
{
    /**
     * 数据统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDataSummary(Request $request){
        $data=[];

        $start_time = date('Y-m-d 00:00:00',time());
        $end_time   = date('Y-m-d 23:59:59',time());

        $data['merchant_num']   = Merchant::count();
        $data['enterprise_num'] = Enterprise::count();
        $data['medicine_num']   = MerchantMedicine::whereIsShop(1)->count();
        $data['today_sum_money']= Orders::whereIsPay(1)
            ->whereBetween('pay_time',[$start_time,$end_time])
            ->sum('pay_amount');
        $data['today_sum_order_num']= Orders::whereBetween('pay_time',[$start_time,$end_time])
            ->count();
        return response()->json(['level'=>'success','message'=>'success','data'=>$data]);
    }

    public function getUserList(Request $request){
        $page           = !is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit          = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $enterprise_id  = $request->get('enterprise_id');
        $keyword        = $request->get('keyword') ?? '';

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;

        if (is_numeric($enterprise_id)){
            $users = User::whereEnterpriseId($enterprise_id);
        } else {
            $users = User::where('id','>',0);
        }

        if ($keyword != ''){
            $nickname   =UserInfo::where('nickname','like','%'.trim($keyword).'%')
                ->orWhere('realname','like','%'.trim($keyword).'%')
                ->pluck('user_id')
                ->toArray();
            $users->whereIn('id',$nickname)
                ->orWhere('phone','like','%'.trim($keyword).'%');
        }

        $users = $users->whereRole(0);

        $pageInfo['total']=$users->count();

        $users = $users->orderByDesc('id')
            ->offset($limit * $page)
            ->limit($limit)
            ->get();
        foreach ($users as $user){
            $user->user_info = UserInfo::getUserInfo($user->id);
            $user->enterprise_name=Enterprise::getEnterpriseName($user->enterprise_id);
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$users,'page_info'=>$pageInfo]);

    }

    public function getMedicineList(Request $request){
        $page           = $request->get('page')  ?? 1;
        $limit          = $request->get('limit') ?? 10;
        $classify_id    = $request->get('classify_id') ?? 0;
        $keyword        = $request->get('keyword') ?? '';
        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        $data=SystemMedicine::where('id','>',0);
        if ($classify_id){
            $data=$data->whereClassifyId($classify_id);
        }

        if ($keyword){
            $data=$data->where('name','like','%'.trim($keyword).'%');
        }
        $pageInfo['total']=$data->count();
        $data=$data->offset($page *$limit)
            ->limit($limit)
            ->get(['id','name','upc','thumb_id','classify_id','first_classify_id','second_classify_id','created_at',]);
        if (count($data) > 0){
            /** @var SystemMedicine $item */
            foreach ($data as $item){
                $item->thumb_url=FileManager::getImgUrl($item->thumb_id);
                $item->classify_name=Classify::getClassifyName($item->classify_id);
                $item->first_classify_name=Classify::getClassifyName($item->first_classify_id);
                $item->second_classify_name=Classify::getClassifyName($item->second_classify_id);
            }
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$data,'page_info'=>$pageInfo]);
    }

    /**
     * 门店销售排行榜
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMerchantLeaderBoard(Request $request){
        $data=[];
        $total=0;
        $start_time = $request->input('start_time') ?? date('Y-m-d 00:00:00',time()-7*24*3600);
        $end_time   = $request->input('end_time')   ?? date('Y-m-d 23:59:59',time());
        $time_info  =[
            'start_time'=>$start_time,
            'end_time'  =>$end_time
        ];

        $merchantIds=Orders::whereIsPay(1)
            ->whereBetween('created_at',[$start_time,$end_time])
            ->pluck('merchant_id')
            ->toArray();
        $merchantIds=array_unique($merchantIds);
        if (count($merchantIds) > 0){
            foreach ($merchantIds as $merchantId){
                $payOrderAmount=Orders::whereIsPay(1)
                    ->whereMerchantId($merchantId)
                    ->whereBetween('created_at',[$start_time,$end_time])
                    ->sum('pay_amount');
                $total=$total+$payOrderAmount;
                $temp=[
                    'amount'=>$payOrderAmount,
                    'merchant_id'=>$merchantId,
                    'merchant_name'=>Merchant::getEnterpriseName($merchantId).'-'.Merchant::getMerchantName($merchantId)
                ];
                array_push($data,$temp);
            }
            arsort($data);
        }
        return response()->json([
            'level'=>'success',
            'message'=>'success',
            'data'=>$data,
            'total_selling_amount'=>$total,
            'time_info'=>$time_info]);
    }

    /**
     * 企业销售排行榜
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseLeaderBoard(Request $request){

        $data=[];
        $total=0;
        $start_time = $request->input('start_time') ?? date('Y-m-d 00:00:00',time()-7*24*3600);
        $end_time   = $request->input('end_time')   ?? date('Y-m-d 23:59:59',time());
        $time_info  =[
            'start_time'=>$start_time,
            'end_time'  =>$end_time
        ];

        $enterpriseIds=Orders::whereIsPay(1)
            ->whereBetween('created_at',[$start_time,$end_time])
            ->pluck('enterprise_id')
            ->toArray();
        $enterpriseIds=array_unique($enterpriseIds);
        if (count($enterpriseIds) > 0){
            foreach ($enterpriseIds as $enterpriseId){
                $payOrderAmount=Orders::whereIsPay(1)
                    ->whereEnterpriseId($enterpriseId)
                    ->whereBetween('created_at',[$start_time,$end_time])
                    ->sum('pay_amount');
                $total=$total+$payOrderAmount;
                $temp=[
                    'amount'=>$payOrderAmount,
                    'enterprise_id'=>$enterpriseId,
                    'enterprise_name'=>Enterprise::getEnterpriseName($enterpriseId)
                ];
                array_push($data,$temp);
            }
            arsort($data);
        }

        return response()->json([
            'level'=>'success',
            'message'=>'success',
            'data'=>$data,
            'total_selling_amount'=>$total,
            'time_info'=>$time_info]);
    }


    public function getMerchantList(Request $request){
        return response()->json(['level'=>'success','message'=>'success','data'=>[]]);
    }

    public static function editGoodsName(){
        echo 'start_implement' . PHP_EOL;
        $systemMedicineList = SystemMedicine::all();
        if(count($systemMedicineList) > 0){
            foreach ($systemMedicineList as $key => $systemMedicine) {
                if($systemMedicine->drug_brand){
                    $medicineName = $systemMedicine->drug_brand . ' ' . $systemMedicine->name;;
                }else{
                    $medicineName = $systemMedicine->name;
                }

                if($systemMedicine->specification){
                    $medicineName .= ' ' . $systemMedicine->specification;
                }

                $systemMedicine->name = $medicineName;
                $systemMedicine->save();

                if($key&1000 == 0){
                    echo 'finish' . $key . 'strip' . PHP_EOL;
                }
            }
        }

        echo 'success';
    }
}
